package com.zhuozhou.jdyc.main.goods.activity;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.zhuozhou.jdyc.R;
import com.zhuozhou.jdyc.api.UserAccountHelper;
import com.zhuozhou.jdyc.base.BaseActivity;
import com.zhuozhou.jdyc.bean.BannerBean;
import com.zhuozhou.jdyc.databinding.ActivityGoodsBinding;
import com.zhuozhou.jdyc.main.goods.adapter.PictureViewPagerAdapte;
import com.zhuozhou.jdyc.main.goods.bean.BasicsCommodityBase;
import com.zhuozhou.jdyc.main.goods.bean.TiHuoBase;
import com.zhuozhou.jdyc.main.goods.viewmodel.GoodsViewModel;
import com.zhuozhou.jdyc.main.main.activity.MainActivity;
import com.zhuozhou.jdyc.main.main.activity.MerchantActivity;
import com.zhuozhou.jdyc.main.main.bean.BasicsShoppingBean;
import com.zhuozhou.jdyc.main.meinfo.bean.ShippingAddressBean;
import com.zhuozhou.jdyc.main.settlement.activity.ShopSettlementActivity;
import com.zhuozhou.jdyc.util.jiami.Base64Util;
import com.zhuozhou.jdyc.util.log.ToastUtils;
import com.zhuozhou.jdyc.wight.dialog.CouponDialog;
import com.zhuozhou.jdyc.wight.dialog.SeeImageDialog;
import com.zhuozhou.jdyc.wight.dialog.SpecificationDialog;
import com.zhuozhou.jdyc.wight.picDialog.PicShowDialog;
import com.zhuozhou.jdyc.wight.picDialog.bean.ImageInfo;

import java.io.Serializable;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Create by Once_ChuXy on 2021/9/5
 * Describe:商品详情
 */
public class GoodsDetailActivity extends BaseActivity<GoodsViewModel, ActivityGoodsBinding> implements ViewPager.OnPageChangeListener {
    private List<String> labelList = new ArrayList<>();
    private PictureViewPagerAdapte pictureAdapter;
    private PictureViewPagerAdapte pictureAdapter0;
    private int mCurrent, count, distributionID, store_id, integral, yihuo_integral;
    private String content;
    private TiHuoBase base;
    public static int PICKUP = 12301;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_goods;
    }

    @Override
    public String setTitleBar() {
        return "商品详情";
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void initView() {
        mViewModel.BasicsCommodityMutableLiveData.observe(this, v -> {
            binding.setShop(v);
            if (baseBundle.getInt("type", 0) == 1) {
                binding.llCoupon.setVisibility(View.VISIBLE);
                binding.tvMoney.setText("品牌特购价 ￥" + v.getData().getDetail().getSpec().get(0).getGoods_price());
            } else if (baseBundle.getInt("type", 0) == 2) {
                binding.llCoupon.setVisibility(View.GONE);
                binding.tvMoneyOld.setVisibility(View.VISIBLE);
                binding.tvIntegral.setVisibility(View.VISIBLE);
                binding.tvIntegralText.setVisibility(View.VISIBLE);
                binding.tvIntegral.setText(v.getData().getDetail().getXiaohao_integral() + "");
                binding.tvIntegralText.setText("积分");
                binding.tvMoney.setText("+ ￥" + v.getData().getDetail().getSpec().get(0).getGoods_price());
                binding.tvMoneyOld.setText("￥" + v.getData().getDetail().getSpec().get(0).getLine_price());
                binding.tvMoneyOld.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//中间
                binding.llPickUp.setVisibility(View.VISIBLE);
            } else if (baseBundle.getInt("type", 0) == 3) {
                binding.llCoupon.setVisibility(View.GONE);
                binding.tvMoney.setVisibility(View.GONE);
                binding.tvIntegral.setVisibility(View.VISIBLE);
                binding.tvIntegralText.setVisibility(View.VISIBLE);
                binding.tvIntegral.setText(v.getData().getDetail().getSpec().get(0).getGoods_price() + "");
                binding.tvIntegralText.setText("易货积分");
            }
            String reputation = getReputation(v.getData().getCommenttypelist());
            binding.tvGoodReputation.setText("好评率" + reputation);
            binding.tvGoodReputation0.setText("好评率" + reputation);
            for (BasicsCommodityBase.DataBean.SpecDataBean.SpecAttrBean.SpecItemsBean item : v.getData().getSpecData().getSpec_attr().get(0).getSpec_items()) {
                labelList.add(item.getSpec_value());
            }
            binding.labels.setLabels(labelList);
            List<BannerBean> bannerList = new ArrayList<>();
            for (String item : v.getData().getDetail().getImgs_url()) {
                bannerList.add(new BannerBean(item));
            }
            binding.picIndex.setText("1/" + v.getData().getDetail().getImgs_url().size());
            if (pictureAdapter == null) {
                pictureAdapter = new PictureViewPagerAdapte(getImageList(v.getData().getDetail().getImgs_url()));
                binding.viewPager.setAdapter(pictureAdapter);
            } else {
                pictureAdapter.notifyDataSetChanged();
            }
            if (v.getData().getCollection() == 0)
                binding.tvAttention.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.icon_attention_w, 0);
            else
                binding.tvAttention.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.icon_attention_aw, 0);
            binding.tvAttention.setOnClickListener(g -> {
                mViewModel.getBasicsCollection(baseBundle.getInt("type"), baseBundle.getString("id"), UserAccountHelper.getUserID());
            });
            binding.tvPickUp.setOnClickListener(l -> {
                Intent intent = new Intent(this, PickUpActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("commodity_id", v.getData().getDetail().getSpec().get(0).getGoods_id() + "");
                intent.putExtras(bundle);
                startActivityForResult(intent, PICKUP);
            });

            binding.llCoupon.setOnClickListener(j -> {
                new CouponDialog(this)
                        .setList(v.getData().getDiscount())
                        .builder()
                        .setOnSureClickListener(i -> {
                            mViewModel.getShopGetDiscount(Integer.parseInt(baseBundle.getString("id")), i.getId(), UserAccountHelper.getUserID());
                        })
                        .show();
            });
            binding.llLabels.setOnClickListener(j -> {
                Intent intent = new Intent(this, EvaluateActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("id", v.getData().getDetail().getId());
                bundle.putInt("type", baseBundle.getInt("type"));
                intent.putExtras(bundle);
                startActivity(intent);
            });

            binding.llChoice.setOnClickListener(j -> {
                if (baseBundle.getInt("type") == 2 && base == null) {
                    ToastUtils.showShort("请先选择提货店铺");
                    return;
                }
                showSpecificationDialog(v);
            });
            binding.tvAddCart.setOnClickListener(j -> {
                if (baseBundle.getInt("type") == 2 && base == null) {
                    ToastUtils.showShort("请先选择提货店铺");
                    return;
                }
                showSpecificationDialog(v);
            });
            binding.tvBuyNow.setOnClickListener(j -> {
                if (baseBundle.getInt("type") == 2 && base == null) {
                    ToastUtils.showShort("请先选择提货店铺");
                    return;
                }
                showSpecificationDialog(v);
            });
            content = v.getData().getDetail().getContent();
            WebSettings settings = binding.webView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setUseWideViewPort(true);
            settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
            settings.setSupportZoom(true);
            settings.setTextZoom(300);//字体大小放大三倍

            binding.webView.setWebChromeClient(new MyWebChromeClient());
            binding.webView.loadUrl("file:///android_asset/goods.html");
            binding.tvMerchant.setOnClickListener(j -> {
                if (baseBundle.getInt("type") == 1) {
                    Intent in = new Intent(this, MerchantActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("id", v.getData().getDetail().getAdmin_id() + "");
                    in.putExtras(bundle);
                    startActivity(in);
                } else if (baseBundle.getInt("type") == 2) {
                    Intent in = new Intent(this, MainActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt("openType", 2);
                    in.putExtras(bundle);
                    startActivity(in);
                } else if (baseBundle.getInt("type") == 3) {
                    Intent in = new Intent(this, MainActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt("openType", 3);
                    in.putExtras(bundle);
                    startActivity(in);
                }
            });
            binding.tvCart.setOnClickListener(j -> {
                Intent in = new Intent(this, MainActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("openType", 4);
                in.putExtras(bundle);
                startActivity(in);
            });
        });
        mViewModel.ShopGetDiscountMutableLiveData.observe(this, v -> {
            ToastUtils.showShort(v.getMsg());
        });
        mViewModel.BasicsShoppingJoinMutableLiveData.observe(this, v -> {
            ToastUtils.showShort(v.getMsg());
        });
        mViewModel.BasicsCollectionMutableLiveData.observe(this, v -> {
            ToastUtils.showShort(this, v.getMsg());
            if (v.getType() == 1) {
                binding.tvAttention.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.icon_attention_aw, 0);
            } else {
                binding.tvAttention.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.icon_attention_w, 0);
            }
        });
        binding.viewPager.addOnPageChangeListener(this);
        binding.mScrollView.setOnScrollChangeListener((v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            if (scrollY >= (binding.mScrollView.getHeight() / 4)) {
                binding.imageTop.setVisibility(View.VISIBLE);
            }
            if (scrollY <= (binding.mScrollView.getHeight() / 4)) {
                binding.imageTop.setVisibility(View.GONE);
            }
        });

        binding.imageTop.setOnClickListener(v -> {
            binding.mScrollView.fullScroll(View.FOCUS_UP);
        });
        binding.tvFriendsShare.setOnClickListener(k -> {
//            ToastUtils.showShort("开发中");
            mViewModel.getPathImg(baseBundle.getInt("type"), baseBundle.getString("id"), UserAccountHelper.getUserID());
        });
        mViewModel.pathImgMutableLiveData.observe(this, v -> {
            new SeeImageDialog(this, Base64Util.stringToBitmap(v)).builder().show();
        });
    }

    //Web视图
    private class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            binding.webView.loadUrl("javascript:setContents(" + "'" + content + "'" + ")");
        }
    }

    public void showSpecificationDialog(BasicsCommodityBase v) {
        new SpecificationDialog(this)
                .setLabels(labelList)
                .setInfo(v)
                .builder()
                .setOnSureClickListener((specification, type, goodWeight) -> {
                    switch (type) {
                        case 0://关闭弹框
                            break;
                        case 1://添加购物车
                            mViewModel.getBasicsShoppingJoin(v.getData().getDetail().getId(), v.getData().getDetail().getAdmin_id(), UserAccountHelper.getUserID(),
                                    specification, v.getData().getDetail().getSpec().get(0).getSpec_sku_id(), v.getData().getDetail().getSpec().get(0).getGoods_weight(),
                                    baseBundle.getInt("type", 0) + "", goodWeight, v.getData().getDetail().getSpec().get(0).getNumberlist(),
                                    distributionID, store_id, integral, yihuo_integral, base == null ? null : base.getId(), v.getData().getDetail().getSpec().get(0).getGoods_no());
                            break;
                        case 2://立即购买
                            List<BasicsShoppingBean.ObjBeanX.ObjBean> list = new ArrayList<>();
                            BasicsShoppingBean.ObjBeanX.ObjBean objBean = new BasicsShoppingBean.ObjBeanX.ObjBean();
                            objBean.setType(baseBundle.getInt("type") + "");
                            List<BasicsShoppingBean.ObjBeanX.ObjBean.ShangpinBean> shopList = new ArrayList<>();
                            BasicsShoppingBean.ObjBeanX.ObjBean.ShangpinBean shop = new BasicsShoppingBean.ObjBeanX.ObjBean.ShangpinBean();
                            shop.setQishou_price(v.getData().getDetail().getQishou_price());
                            shop.setHuoyun(v.getData().getDetail().getWuliu_price());
                            shop.setWuliu(v.getData().getDetail().getWuliu_price());
                            shop.setIntegral(v.getData().getDetail().getXiaohao_integral());
                            shop.setYibi(v.getData().getDetail().getXiaohao_integral());
                            shop.setNumber(goodWeight);
                            shop.setName(v.getData().getDetail().getName());
                            shop.setSku(v.getData().getDetail().getSpec().get(0).getSpec_sku_id());
                            shop.setSkustring(v.getData().getDetail().getSpec_rel().get(0).getSpec_value());
                            shop.setGoods_weight(v.getData().getDetail().getSpec().get(0).getGoods_weight());
                            shop.setGoods_price(v.getData().getDetail().getSpec().get(0).getGoods_price());
                            shop.setSpec_image(v.getData().getSpecData().getSpec_list().get(0).getForm().getImgshow());
                            shop.setUnit(v.getData().getDetail().getUnit());
                            shopList.add(shop);
                            objBean.setShangpin(shopList);
                            BasicsCommodityBase.DataBean.DiscountBean discountBean =  new BasicsCommodityBase.DataBean.DiscountBean();
                            discountBean.setId(0);
                            objBean.setDiscountSelect(discountBean);
                            objBean.setDiscount(v.getData().getDiscount());
                            objBean.setType(baseBundle.getInt("type") + "");
                            list.add(objBean);
                            Intent intent = new Intent(this, ShopSettlementActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("shop", (Serializable) list);
                            intent.putExtras(bundle);
                            startActivity(intent);
                            break;
                    }
                })
                .show();
    }

    public List<com.zhuozhou.jdyc.wight.customlayout.CornersImageView> getImageList(List<String> list) {
        count = list.size();
        List<com.zhuozhou.jdyc.wight.customlayout.CornersImageView> imageLists = new ArrayList<>();
        List<ImageInfo> imageInfosList = new ArrayList<>();
        for (String url : list) {
            View view = LayoutInflater.from(this).inflate(R.layout.viewpager_imageview, null);
            com.zhuozhou.jdyc.wight.customlayout.CornersImageView imageView = view.findViewById(R.id.house_show_img);
            Glide.with(this).load(url).into(imageView);
            imageLists.add(imageView);
            imageInfosList.add(new ImageInfo(url));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setOnClickListener(v -> {
                PicShowDialog dialog = new PicShowDialog(this, imageInfosList, mCurrent);
                dialog.show();
            });
        }
        return imageLists;
    }

    public String getReputation(BasicsCommodityBase.DataBean.CommenttypelistBean base) {
        if ((base.getChaping() + base.getHaoping() + base.getZhongping()) == 0) {
            return "100%";
        }
        int a = base.getHaoping() / (base.getChaping() + base.getHaoping() + base.getZhongping());
        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMaximumFractionDigits(2);//这个是保存结果到小数点后几位，但是特别声明：这个结果已经先＊100了。
        return nf.format(a);
    }

    @Override
    public void initData(Bundle bundle) {
        if (bundle.getInt("type") == 1)
            mViewModel.getBasicsCommodity("1", bundle.getString("id"), UserAccountHelper.getUserID());
        else if (bundle.getInt("type") == 2)
            mViewModel.getJiFenCommodity("2", bundle.getString("id"), UserAccountHelper.getUserID());
        else if (bundle.getInt("type") == 3)
            mViewModel.getYiHuoCommodity("3", bundle.getString("id"), UserAccountHelper.getUserID());
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        mCurrent = position;
        binding.picIndex.setText(position + 1 + "/" + count);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == PICKUP) {
            base = (TiHuoBase) data.getExtras().getSerializable("data");
            binding.tvPickUp.setText(base.getNickname());
        }
    }
}
